package com.example.demo.tokenbucket;

import com.example.demo.redis.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Aspect
@Component
@Slf4j
public class TokenAspect {
    // Lua脚本（与之前的相同）
    private static final String LUA_SCRIPT =
            "local currentValue = redis.call('GET', KEYS[1]); " +
                    "if tonumber(currentValue) > 1 then " +
                    "   redis.call('SET', KEYS[1], tonumber(currentValue) - 1); " +
                    "   return redis.call('GET', KEYS[1]); " +
                    "else " +
                    "   return 0; " +
                    "end";
    @Autowired
    private RedisUtil redisUtil;

    @Around("@annotation(requireToken)")
    public Object checkToken(ProceedingJoinPoint joinPoint, RequireToken requireToken) throws Throwable {
        String result;
        Long canToken = redisUtil.exeLua(LUA_SCRIPT, "token");
        log.info("剩余令牌个数{}", canToken);
        if (canToken != 0) {
            // 继续执行原方法
            return joinPoint.proceed();
        } else {
            result = "未抢到令牌，降级方案";
            // 可以在这里执行降级逻辑，或者直接返回结果
            return result;
        }
    }
}